package com.jzt.gateway.filter;

import com.jzt.gateway.GlobalConstant;
import com.jzt.gateway.collect.ICollectLoginData;
import com.jzt.gateway.collect.ICollectRegisterData;
import com.jzt.gateway.config.AuthConfig;
import com.jzt.gateway.config.JwtTokenConfig;
import com.jzt.gateway.config.ServersConfig;
import com.jzt.gateway.dto.request.AbstractLogin;
import com.jzt.gateway.dto.request.AccountRegisterReq;
import com.jzt.gateway.entity.Account;
import com.jzt.gateway.model.AccountInfo;
import com.jzt.gateway.service.AuthService;
import com.jzt.gateway.service.LoginService;
import com.jzt.gateway.service.RegisterService;
import com.jzt.gateway.utils.ExchangeUtils;
import com.jzt.gateway.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseCookie;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/06/16 11:04 <br/>
 */
@Component
@Slf4j
public class AuthenticationGlobalFilter implements GlobalFilter, Ordered {
    private static final int Order = Integer.MAX_VALUE - 2;
    private static final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
    /**
     * Cookie延长的过期时间(单位秒)
     */
    private static final long CookieExpPlusSeconds = 300;

    @Autowired
    private ServersConfig serversConfig;
    @Autowired
    private LoginService loginService;
    @Autowired
    private AuthService authService;
    @Autowired
    private RegisterService registerService;

    private final List<ICollectLoginData> collectLoginDataList;
    private final List<ICollectRegisterData> collectRegisterDataList;

    public AuthenticationGlobalFilter(@Autowired List<ICollectLoginData> collectLoginDataList, @Autowired List<ICollectRegisterData> collectRegisterDataList) {
        collectLoginDataList.sort((o1, o2) -> {
            int res = o1.order() - o2.order();
            return Integer.compare(res, 0);
        });
        this.collectLoginDataList = collectLoginDataList;
        collectRegisterDataList.sort((o1, o2) -> {
            int res = o1.order() - o2.order();
            return Integer.compare(res, 0);
        });
        this.collectRegisterDataList = collectRegisterDataList;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // log.debug("{}", exchange.getRequest().getPath());
        // 当前Route
        final Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (route == null || StringUtils.isBlank(route.getId())) {
            log.warn("RouteID获取失败");
            return chain.filter(exchange);
        }
        // 当前AuthConfig
        final AuthConfig authConfig = serversConfig.getAuthConfig(route.getId());
        if (authConfig == null) {
            log.warn("AuthConfig获取失败");
            return chain.filter(exchange);
        }
        // 当前JwtTokenConfig
        final JwtTokenConfig jwtTokenConfig = authConfig.getJwtTokenConfig();
        if (jwtTokenConfig == null) {
            log.warn("JwtTokenConfig获取失败");
            return chain.filter(exchange);
        }
        final HttpMethod httpMethod = exchange.getRequest().getMethod();
        final String path = exchange.getRequest().getPath().value();
        // 0:鉴权 1:登录 2:注册 3:登出
        int filterType = 0;
        if (Objects.equals(authConfig.getLoginPath(), path) && Objects.equals(httpMethod, HttpMethod.POST)) {
            filterType = 1;
            // 登录
        } else if (Objects.equals(authConfig.getRegisterPath(), path) && Objects.equals(httpMethod, HttpMethod.POST)) {
            // 注册
            filterType = 2;
        } else if (Objects.equals(authConfig.getLoginOutPath(), path)) {
            // 登出
            filterType = 3;
        }
        if (filterType != 0) {
            final int bizType = filterType;
            return ServerWebExchangeUtils.cacheRequestBody(exchange, serverHttpRequest -> {
                ServerWebExchange newExchange = ExchangeUtils.modifyRequestHeaders(exchange, serverHttpRequest);
                // 获取 Request Body 参考 ReadBodyPredicateFactory
                Mono<String> mono = ServerRequest.create(newExchange, messageReaders)
                        .bodyToMono(String.class)
                        .doOnNext(body -> {
                            try {
                                // log.info("body -> {}", body);
                                newExchange.getAttributes().put(GlobalConstant.CACHED_REQUEST_BODY_STR_ATTR, body);
                            } catch (Exception e) {
                                log.error("缓存请求body处理失败", e);
                            }
                        })
                        .doFinally(signalType -> {
                            try {
                                switch (bizType) {
                                    case 1:
                                        // 登录
                                        doLogin(newExchange, authConfig, jwtTokenConfig);
                                        break;
                                    case 2:
                                        // 注册
                                        doPreRegister(newExchange, authConfig, jwtTokenConfig);
                                        break;
                                    case 3:
                                        // 登出
                                        doLoginOut(newExchange, authConfig, jwtTokenConfig);
                                        break;
                                }
                                newExchange.getAttributes().put(GlobalConstant.AUTHENTICATION_EXEC_ATTR, true);
                            } catch (Exception e) {
                                log.error("{}处理失败", bizType == 1 ? "登录" : bizType == 2 ? "注册" : "登出", e);
                            }
                        });
                // 合并Mono
                return Flux.merge(mono, chain.filter(newExchange)).then(Mono.create(monoSink -> {
                    if (bizType == 2) {
                        try {
                            doPostRegister(newExchange, authConfig, jwtTokenConfig);
                        } catch (Exception e) {
                            log.error("注册处理失败", e);
                        }
                    }
                    monoSink.success();
                }));
            });
        }
        // 鉴权
        ServerWebExchange newExchange = exchange;
        try {
            newExchange = doAuth(exchange, authConfig, jwtTokenConfig);
            newExchange.getAttributes().put(GlobalConstant.AUTHENTICATION_EXEC_ATTR, true);
        } catch (Exception e) {
            log.error("鉴权处理失败", e);
        }
        return chain.filter(newExchange);
    }

    /**
     * 登录逻辑处理
     */
    protected void doLogin(ServerWebExchange newExchange, AuthConfig authConfig, JwtTokenConfig jwtTokenConfig) {
        // 收集登录信息
        AbstractLogin loginInfo = null;
        for (ICollectLoginData collectLoginData : collectLoginDataList) {
            if (collectLoginData.support(newExchange)) {
                loginInfo = collectLoginData.getLoginInfo(newExchange);
                break;
            }
        }
        if (loginInfo == null) {
            return;
        }
        // 验证登录
        AccountInfo account = loginService.authentication(authConfig, loginInfo);
        if (account == null) {
            return;
        }
        // 生成Token
        try {
            String token = JwtTokenUtils.createToken(account, jwtTokenConfig);
            if (jwtTokenConfig.isUseCookie()) {
                ResponseCookie cookie = ResponseCookie.from(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, token)
                        .path("/")
                        .maxAge(jwtTokenConfig.getTokenValidity().plus(Duration.ofSeconds(CookieExpPlusSeconds)))
                        .build();
                List<String> cookies = newExchange.getRequest().getHeaders().get(HttpHeaders.COOKIE);
                if (cookies == null) {
                    cookies = new ArrayList<>();
                }
                cookies = cookies.stream()
                        .filter(value -> value == null || !value.toLowerCase().startsWith(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME + "="))
                        .collect(Collectors.toList());
                cookies.add(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME + "=" + token);
                newExchange.getRequest().getHeaders().put(HttpHeaders.COOKIE, cookies);
                // newExchange.getRequest().getHeaders().add(HttpHeaders.COOKIE, GlobalConstant.GATEWAY_AUTH_TOKEN_NAME + "=" + token);
                newExchange.getResponse().addCookie(cookie);
            } else {
                newExchange.getRequest().getHeaders().put(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, Collections.singletonList(token));
                newExchange.getResponse().getHeaders().put(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, Collections.singletonList(token));
            }
        } catch (Exception e) {
            log.error("生成Token失败", e);
        }
    }

    /**
     * 注册逻辑处理 - pre(透传给服务之前)
     */
    protected void doPreRegister(ServerWebExchange newExchange, AuthConfig authConfig, JwtTokenConfig jwtTokenConfig) {
        // 收集注册信息
        AccountRegisterReq accountRegisterReq = null;
        for (ICollectRegisterData collectRegisterData : collectRegisterDataList) {
            if (collectRegisterData.support(newExchange)) {
                accountRegisterReq = collectRegisterData.getAccountRegister(newExchange);
                break;
            }
        }
        Account account = registerService.preRegister(accountRegisterReq, authConfig);
        newExchange.getAttributes().put(GlobalConstant.CACHED_REQUEST_REGISTER_ACCOUNT_ATTR, account);
        if (account != null) {
            newExchange.getRequest().getHeaders().put(GlobalConstant.GATEWAY_ONE_ID_NAME, Collections.singletonList(account.getOneId()));
        }
    }

    /**
     * 注册逻辑处理 - post(透传给服务之后)
     */
    protected void doPostRegister(ServerWebExchange newExchange, AuthConfig authConfig, JwtTokenConfig jwtTokenConfig) {
        Account account = newExchange.getAttribute(GlobalConstant.CACHED_REQUEST_REGISTER_ACCOUNT_ATTR);
        List<String> userAgentIds = newExchange.getResponse().getHeaders().get(GlobalConstant.GATEWAY_USER_AGENT_ID_NAME);
        if (account == null || userAgentIds == null || userAgentIds.isEmpty()) {
            return;
        }
        for (String userAgentId : userAgentIds) {
            if (StringUtils.isNotBlank(userAgentId)) {
                account.setUserAgentId(userAgentId);
            }
        }
        if (StringUtils.isBlank(account.getUserAgentId())) {
            return;
        }
        registerService.postRegister(account);
    }

    /**
     * 登出逻辑处理
     */
    protected void doLoginOut(ServerWebExchange newExchange, AuthConfig authConfig, JwtTokenConfig jwtTokenConfig) {
        // 删除 token Cookie
        ResponseCookie delCookie = ResponseCookie.from(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, "")
                .path("/")
                .maxAge(Duration.ofSeconds(0))
                .build();
        newExchange.getResponse().addCookie(delCookie);
    }

    /**
     * 鉴权逻辑处理
     */
    protected ServerWebExchange doAuth(ServerWebExchange exchange, AuthConfig authConfig, JwtTokenConfig jwtTokenConfig) {
        List<String> tokens = new ArrayList<>();
        if (jwtTokenConfig.isUseCookie()) {
            List<HttpCookie> cookies = exchange.getRequest().getCookies().get(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME);
            if (cookies != null) {
                cookies.forEach(cookie -> tokens.add(cookie.getValue()));
            }
        } else {
            List<String> headers = exchange.getRequest().getHeaders().get(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME);
            if (headers != null) {
                tokens.addAll(headers);
            }
        }
        AuthService.AuthRes authRes = authService.auth(tokens, jwtTokenConfig);
        if (authRes.getAccountInfo() == null) {
            // 认证失败
            exchange = ExchangeUtils.modifyRequestHeaders(exchange, exchange.getRequest());
            if (jwtTokenConfig.isUseCookie()) {
                // 删除Cookie
                List<String> cookies = exchange.getRequest().getHeaders().get(HttpHeaders.COOKIE);
                if (cookies != null) {
                    cookies = cookies.stream()
                            .filter(value -> value == null || !value.toLowerCase().startsWith(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME + "="))
                            .collect(Collectors.toList());
                    exchange.getRequest().getHeaders().put(HttpHeaders.COOKIE, cookies);
                }
                // ResponseCookie delCookie = ResponseCookie.from(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, tokens.isEmpty() ? "" : tokens.get(0))
                //         .path("/")
                //         .maxAge(Duration.ofSeconds(0))
                //         .build();
                // exchange.getResponse().addCookie(delCookie);
            } else {
                // 删除Head
                exchange.getRequest().getHeaders().remove(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME);
            }
            log.info("认证失败 - {}", exchange.getRequest().getPath().toString());
            return exchange;
        }
        log.info("认证成功 - {}", exchange.getRequest().getPath().toString());
        // 认证成功
        if (authRes.getNewToken() != null) {
            if (jwtTokenConfig.isUseCookie()) {
                ResponseCookie cookie = ResponseCookie.from(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, authRes.getNewToken())
                        .path("/")
                        .maxAge(jwtTokenConfig.getTokenValidity().plus(Duration.ofSeconds(CookieExpPlusSeconds)))
                        .build();
                exchange.getResponse().addCookie(cookie);
            } else {
                exchange.getResponse().getHeaders().put(GlobalConstant.GATEWAY_AUTH_TOKEN_NAME, Collections.singletonList(authRes.getNewToken()));
            }
        }
        return exchange;
    }

    @Override
    public int getOrder() {
        return Order;
    }
}
